<template>
  <div class="product-detail-page">
    <div class="container">
      <!-- 面包屑导航 -->
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/products' }">商品列表</el-breadcrumb-item>
        <el-breadcrumb-item>{{ product?.name }}</el-breadcrumb-item>
      </el-breadcrumb>

      <div v-if="product" class="product-detail-content">
        <!-- 商品主要信息 -->
        <div class="product-main">
          <!-- 商品图片 -->
          <div class="product-images">
            <div class="main-image">
              <img :src="currentImage" :alt="product.name" />
              <div class="image-zoom" @click="openImageViewer">
                <el-icon><ZoomIn /></el-icon>
              </div>
            </div>
            
            <div v-if="product.images && product.images.length > 1" class="thumbnail-list">
              <div 
                v-for="(image, index) in product.images"
                :key="index"
                class="thumbnail"
                :class="{ active: currentImage === image }"
                @click="currentImage = image"
              >
                <img :src="image" :alt="`${product.name} ${index + 1}`" />
              </div>
            </div>
          </div>

          <!-- 商品信息 -->
          <div class="product-info">
            <div class="product-header">
              <h1 class="product-title">{{ product.name }}</h1>
              <div class="product-tags">
                <el-tag v-if="product.isNew" type="success">新品</el-tag>
                <el-tag v-if="product.isHot" type="danger">热销</el-tag>
                <el-tag v-if="product.discount" type="warning">特价</el-tag>
              </div>
            </div>

            <div class="product-price">
              <span class="current-price">¥{{ product.price }}</span>
              <span v-if="product.originalPrice" class="original-price">
                ¥{{ product.originalPrice }}
              </span>
              <span v-if="product.discount" class="discount-badge">
                省¥{{ product.originalPrice - product.price }}
              </span>
            </div>

            <div class="product-meta">
              <div class="meta-item">
                <span class="label">销量：</span>
                <span class="value">{{ product.sales || 0 }}</span>
              </div>
              <div class="meta-item">
                <span class="label">评分：</span>
                <el-rate 
                  v-model="product.rating" 
                  disabled 
                  show-score 
                  text-color="#ff9900"
                />
              </div>
            </div>

            <div class="product-description">
              <h3>商品描述</h3>
              <p>{{ product.description }}</p>
            </div>

            <!-- 商品选项 -->
            <div class="product-options">
              <div v-if="product.variants" class="option-group">
                <h4>规格选择</h4>
                <div class="variant-options">
                  <el-button
                    v-for="variant in product.variants"
                    :key="variant.id"
                    :type="selectedVariant?.id === variant.id ? 'primary' : 'default'"
                    @click="selectedVariant = variant"
                  >
                    {{ variant.name }}
                  </el-button>
                </div>
              </div>

              <div class="quantity-selector">
                <h4>购买数量</h4>
                <el-input-number 
                  v-model="quantity" 
                  :min="1" 
                  :max="99"
                  size="large"
                />
              </div>
            </div>

            <!-- 操作按钮 -->
            <div class="product-actions">
              <el-button 
                type="primary" 
                size="large"
                :loading="isAdding"
                @click="addToCart"
                class="action-btn"
              >
                <el-icon><ShoppingCart /></el-icon>
                加入购物车
              </el-button>
              
              <el-button 
                type="success" 
                size="large"
                @click="buyNow"
                class="action-btn"
              >
                <el-icon><ShoppingBag /></el-icon>
                立即购买
              </el-button>
              
              <el-button 
                :icon="isFavorite ? StarFilled : Star"
                size="large"
                @click="toggleFavorite"
                class="favorite-btn"
              />
            </div>
          </div>
        </div>

        <!-- 商品详细描述 -->
        <div class="product-details">
          <el-tabs v-model="activeTab" class="detail-tabs">
            <el-tab-pane label="详细描述" name="description">
              <div class="detail-content">
                <h3>商品详情</h3>
                <div class="detail-text">
                  <p>{{ product.fullDescription || product.description }}</p>
                  <div v-if="product.features" class="features-list">
                    <h4>商品特点：</h4>
                    <ul>
                      <li v-for="feature in product.features" :key="feature">
                        {{ feature }}
                      </li>
                    </ul>
                  </div>
                </div>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="规格参数" name="specs">
              <div class="detail-content">
                <h3>规格参数</h3>
                <table v-if="product.specifications" class="specs-table">
                  <tr v-for="(value, key) in product.specifications" :key="key">
                    <td class="spec-label">{{ key }}</td>
                    <td class="spec-value">{{ value }}</td>
                  </tr>
                </table>
              </div>
            </el-tab-pane>
            
            <el-tab-pane label="用户评价" name="reviews">
              <div class="detail-content">
                <h3>用户评价</h3>
                <div class="reviews-summary">
                  <div class="rating-overview">
                    <div class="rating-score">{{ product.rating || 4.5 }}</div>
                    <el-rate :model-value="product.rating || 4.5" disabled />
                    <div class="rating-text">基于 {{ product.reviewCount || 128 }} 条评价</div>
                  </div>
                </div>
                
                <div class="reviews-list">
                  <div v-for="review in mockReviews" :key="review.id" class="review-item">
                    <div class="review-header">
                      <span class="reviewer-name">{{ review.username }}</span>
                      <el-rate :model-value="review.rating" disabled size="small" />
                      <span class="review-date">{{ review.date }}</span>
                    </div>
                    <div class="review-content">{{ review.content }}</div>
                  </div>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>

        <!-- 相关推荐 -->
        <div class="related-products">
          <h2 class="section-title">相关推荐</h2>
          <div class="related-grid">
            <ProductCard 
              v-for="item in relatedProducts"
              :key="item.id"
              :product="item"
            />
          </div>
        </div>
      </div>

      <!-- 商品不存在 -->
      <div v-else class="product-not-found">
        <el-empty description="商品不存在或已下架">
          <el-button type="primary" @click="$router.push('/products')">
            返回商品列表
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 图片查看器 -->
    <el-image-viewer
      v-if="showImageViewer"
      :url-list="product?.images || [currentImage]"
      :initial-index="imageViewerIndex"
      @close="closeImageViewer"
    />
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { store } from '@/store'
import { ElMessage } from 'element-plus'
import ProductCard from '@/components/ProductCard.vue'
import { 
  ZoomIn,
  ShoppingCart, 
  ShoppingBag,
  Star,
  StarFilled
} from '@element-plus/icons-vue'

export default {
  name: 'ProductDetail',
  components: {
    ProductCard,
    ZoomIn,
    ShoppingCart,
    ShoppingBag,
    Star,
    StarFilled
  },
  props: {
    id: {
      type: String,
      required: true
    }
  },
  setup(props) {
    const route = useRoute()
    const router = useRouter()
    
    // 响应式数据
    const product = ref(null)
    const currentImage = ref('')
    const selectedVariant = ref(null)
    const quantity = ref(1)
    const isAdding = ref(false)
    const isFavorite = ref(false)
    const activeTab = ref('description')
    const showImageViewer = ref(false)
    const imageViewerIndex = ref(0)
    
    // 模拟商品数据
    const mockProducts = {
      1: {
        id: 1,
        name: '高端猫粮 海洋鱼味',
        description: '精选深海鱼类，营养丰富，口感佳，适合各个年龄段的猫咪',
        fullDescription: '这款高端猫粮采用新鲜的深海鱼类作为主要蛋白质来源，富含Omega-3脂肪酸，有助于维护猫咪的毛发光泽和皮肤健康。科学配比的营养成分，满足猫咪日常所需。',
        price: 299,
        originalPrice: 399,
        image: require('@/assets/images/AD0I9ruEDBAEGAAg6Z-B_wUojMjq3QYwgAY4gAY_400x400.png'),
        images: [
          require('@/assets/images/AD0I9ruEDBAEGAAg6Z-B_wUojMjq3QYwgAY4gAY_400x400.png'),
          require('@/assets/images/AD0I9ruEDBAEGAAgsZ-B_wUom8Kd-wQwgAY4gAY_400x400.png')
        ],
        category: 'food',
        sales: 1250,
        rating: 4.8,
        reviewCount: 234,
        isNew: false,
        isHot: true,
        discount: true,
        features: [
          '深海鱼类蛋白质',
          '富含Omega-3',
          '无人工添加剂',
          '适合全年龄段'
        ],
        specifications: {
          '品牌': '优选宠物',
          '重量': '2kg',
          '保质期': '18个月',
          '适用对象': '成年猫',
          '主要成分': '深海鱼肉、谷物、维生素'
        },
        variants: [
          { id: 1, name: '2kg装', price: 299 },
          { id: 2, name: '5kg装', price: 688 },
          { id: 3, name: '10kg装', price: 1299 }
        ]
      }
      // 可以添加更多商品数据
    }
    
    // 模拟评价数据
    const mockReviews = ref([
      {
        id: 1,
        username: '爱猫人士',
        rating: 5,
        date: '2024-01-15',
        content: '非常好的猫粮，我家猫咪很喜欢吃，毛发也变得更亮了。'
      },
      {
        id: 2,
        username: '宠物达人',
        rating: 4,
        date: '2024-01-10',
        content: '品质不错，价格也合理，会继续购买。'
      },
      {
        id: 3,
        username: '小鱼干',
        rating: 5,
        date: '2024-01-08',
        content: '包装很好，物流也快，猫咪吃了没有不良反应。'
      }
    ])
    
    // 相关商品
    const relatedProducts = ref([
      {
        id: 2,
        name: '智能宠物玩具球',
        description: '自动滚动，陪伴宠物玩耍',
        price: 129,
        image: 'https://manymart.com.hk/cdn/shop/files/image_22fcf830-c5cd-4e72-a78b-7a4b8bce5fee.jpg?v=1712771610&width=713',
        category: 'toys'
      },
      {
        id: 3,
        name: '宠物洗护套装',
        description: '温和无刺激，深层清洁护理',
        price: 89,
        originalPrice: 120,
        image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQwj3Kark-4F1AqjhuUIIWg7islNDNfzBj8Ag&s',
        category: 'care'
      },
      {
        id: 5,
        name: '营养宠物零食',
        description: '天然健康，训练奖励必备',
        price: 45,
        image: require('@/assets/images/AD0I9ruEDBAEGAAgsZ-B_wUom8Kd-wQwgAY4gAY_400x400.png'),
        category: 'food'
      },
      {
        id: 6,
        name: '舒适宠物窝',
        description: '柔软舒适，给宠物温暖的家',
        price: 188,
        image: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQUMWSmj5v8v0i19_d61a-Vkf59wpIOLdzLaw&s',
        category: 'accessories'
      }
    ])
    
    // 计算当前价格（考虑规格）
    const currentPrice = computed(() => {
      if (selectedVariant.value) {
        return selectedVariant.value.price
      }
      return product.value?.price || 0
    })
    
    // 方法
    const loadProduct = async (productId) => {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 500))
        
        product.value = mockProducts[productId]
        if (product.value) {
          currentImage.value = product.value.image
          if (product.value.variants && product.value.variants.length > 0) {
            selectedVariant.value = product.value.variants[0]
          }
        }
      } catch (error) {
        console.error('加载商品失败:', error)
        ElMessage.error('加载商品失败')
      }
    }
    
    const addToCart = async () => {
      if (!product.value) return
      
      isAdding.value = true
      try {
        await new Promise(resolve => setTimeout(resolve, 300))
        
        const cartItem = {
          ...product.value,
          quantity: quantity.value,
          variant: selectedVariant.value,
          price: currentPrice.value
        }
        
        store.addToCart(cartItem)
        ElMessage.success(`${product.value.name} 已添加到购物车`)
      } catch (error) {
        ElMessage.error('添加失败，请重试')
      } finally {
        isAdding.value = false
      }
    }
    
    const buyNow = () => {
      addToCart().then(() => {
        router.push('/checkout')
      })
    }
    
    const toggleFavorite = () => {
      isFavorite.value = !isFavorite.value
      ElMessage.success(
        isFavorite.value ? '已添加到收藏' : '已取消收藏'
      )
    }
    
    const openImageViewer = () => {
      if (product.value?.images) {
        imageViewerIndex.value = product.value.images.indexOf(currentImage.value)
      }
      showImageViewer.value = true
    }
    
    const closeImageViewer = () => {
      showImageViewer.value = false
    }
    
    // 监听路由参数变化
    watch(() => props.id, (newId) => {
      if (newId) {
        loadProduct(newId)
      }
    }, { immediate: true })
    
    onMounted(() => {
      const productId = props.id || route.params.id
      if (productId) {
        loadProduct(productId)
      }
    })
    
    return {
      product,
      currentImage,
      selectedVariant,
      quantity,
      isAdding,
      isFavorite,
      activeTab,
      showImageViewer,
      imageViewerIndex,
      mockReviews,
      relatedProducts,
      currentPrice,
      addToCart,
      buyNow,
      toggleFavorite,
      openImageViewer,
      closeImageViewer,
      // Element Plus icons
      ZoomIn,
      ShoppingCart,
      ShoppingBag,
      Star,
      StarFilled
    }
  }
}
</script>

<style scoped>
.product-detail-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding: 30px 0;
}

.el-breadcrumb {
  margin-bottom: 30px;
}

.product-detail-content {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

/* 商品主要信息 */
.product-main {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 60px;
  padding: 40px;
}

.product-images {
  position: sticky;
  top: 100px;
  height: fit-content;
}

.main-image {
  position: relative;
  width: 100%;
  height: 400px;
  border-radius: 12px;
  overflow: hidden;
  margin-bottom: 20px;
  background: #f8f9fa;
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.image-zoom {
  position: absolute;
  top: 15px;
  right: 15px;
  width: 40px;
  height: 40px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.3s ease;
}

.image-zoom:hover {
  background: rgba(255, 255, 255, 0.95);
  transform: scale(1.1);
}

.thumbnail-list {
  display: flex;
  gap: 15px;
  overflow-x: auto;
}

.thumbnail {
  flex-shrink: 0;
  width: 80px;
  height: 80px;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border-color 0.3s ease;
}

.thumbnail.active {
  border-color: #FF8C00;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-info {
  padding-top: 20px;
}

.product-header {
  margin-bottom: 20px;
}

.product-title {
  font-size: 2rem;
  font-weight: bold;
  color: #333;
  margin-bottom: 15px;
  line-height: 1.3;
}

.product-tags {
  display: flex;
  gap: 10px;
}

.product-price {
  margin-bottom: 25px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.current-price {
  font-size: 2.2rem;
  font-weight: bold;
  color: #f56565;
}

.original-price {
  font-size: 1.2rem;
  color: #999;
  text-decoration: line-through;
}

.discount-badge {
  background: #f56565;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9rem;
}

.product-meta {
  margin-bottom: 25px;
  display: flex;
  gap: 30px;
}

.meta-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.label {
  font-weight: 500;
  color: #666;
}

.value {
  color: #333;
}

.product-description {
  margin-bottom: 30px;
}

.product-description h3 {
  font-size: 1.2rem;
  color: #333;
  margin-bottom: 10px;
}

.product-description p {
  color: #666;
  line-height: 1.6;
}

.product-options {
  margin-bottom: 40px;
}

.option-group {
  margin-bottom: 25px;
}

.option-group h4,
.quantity-selector h4 {
  font-size: 1.1rem;
  color: #333;
  margin-bottom: 15px;
}

.variant-options {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.quantity-selector {
  margin-bottom: 25px;
}

.product-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.action-btn {
  flex: 1;
  min-width: 160px;
  height: 50px;
  font-size: 1.1rem;
}

.favorite-btn {
  width: 50px;
  height: 50px;
  flex-shrink: 0;
}

/* 详细信息tabs */
.product-details {
  border-top: 1px solid #eee;
  padding: 40px;
}

.detail-content {
  padding-top: 20px;
}

.detail-content h3 {
  font-size: 1.3rem;
  color: #333;
  margin-bottom: 20px;
}

.detail-text {
  color: #666;
  line-height: 1.6;
}

.features-list {
  margin-top: 20px;
}

.features-list h4 {
  color: #333;
  margin-bottom: 10px;
}

.features-list ul {
  list-style: none;
  padding: 0;
}

.features-list li {
  padding: 5px 0;
  position: relative;
  padding-left: 20px;
}

.features-list li::before {
  content: '•';
  color: #FF8C00;
  position: absolute;
  left: 0;
}

.specs-table {
  width: 100%;
  border-collapse: collapse;
}

.specs-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
}

.spec-label {
  background: #f8f9fa;
  font-weight: 500;
  color: #333;
  width: 150px;
}

.spec-value {
  color: #666;
}

/* 评价部分 */
.reviews-summary {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
}

.rating-overview {
  display: flex;
  align-items: center;
  gap: 15px;
}

.rating-score {
  font-size: 2.5rem;
  font-weight: bold;
  color: #FF8C00;
}

.rating-text {
  color: #666;
}

.reviews-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.review-item {
  padding: 20px;
  border: 1px solid #eee;
  border-radius: 8px;
}

.review-header {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-bottom: 10px;
}

.reviewer-name {
  font-weight: 500;
  color: #333;
}

.review-date {
  color: #999;
  font-size: 0.9rem;
  margin-left: auto;
}

.review-content {
  color: #666;
  line-height: 1.5;
}

/* 相关推荐 */
.related-products {
  padding: 40px;
  border-top: 1px solid #eee;
}

.section-title {
  font-size: 1.5rem;
  color: #333;
  margin-bottom: 30px;
  text-align: center;
}

.related-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 25px;
}

.product-not-found {
  padding: 60px 20px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 1024px) {
  .product-main {
    grid-template-columns: 1fr;
    gap: 40px;
  }
  
  .product-images {
    position: static;
  }
}

@media (max-width: 768px) {
  .product-detail-page {
    padding: 20px 0;
  }
  
  .product-main,
  .product-details,
  .related-products {
    padding: 20px;
  }
  
  .product-title {
    font-size: 1.6rem;
  }
  
  .current-price {
    font-size: 1.8rem;
  }
  
  .product-meta {
    flex-direction: column;
    gap: 15px;
  }
  
  .product-actions {
    flex-direction: column;
  }
  
  .action-btn {
    min-width: auto;
  }
  
  .rating-overview {
    flex-direction: column;
    text-align: center;
  }
  
  .related-grid {
    grid-template-columns: 1fr;
  }
}

@media (max-width: 480px) {
  .main-image {
    height: 300px;
  }
  
  .thumbnail {
    width: 60px;
    height: 60px;
  }
  
  .variant-options {
    flex-direction: column;
  }
  
  .variant-options .el-button {
    width: 100%;
  }
}

/* 深度选择器样式 */
:deep(.detail-tabs .el-tabs__header) {
  margin-bottom: 0;
}

:deep(.detail-tabs .el-tabs__nav-wrap::after) {
  height: 1px;
}
</style>
